package com.maxd.service.timedTask;

import com.maxd.model.*;
import com.maxd.respository.helpTask.HelpSendOrderRepository;
import com.maxd.respository.helpTask.HelpTakeOrderRepository;
import com.maxd.respository.helpTask.HelpTaskJpaRepository;
import com.maxd.respository.helpTask.HelpTaskRepository;
import com.maxd.respository.timedTask.TimedTaskJpaRepository;
import com.maxd.respository.timedTask.TimedTaskRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.helpTask.HelpTaskService;
import com.maxd.service.helpTask.HelpUserScoreDetailsService;
import com.maxd.service.helpTask.HelpUserScoreService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.utils.AmountCalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务类
 */
@Service
public class TimedTaskServiceImpl implements TimedTaskService {

    @Autowired
    private TimedTaskRepository timedTaskRepository;
    @Autowired
    private TimedTaskJpaRepository timedTaskJpaRepository;
    @Autowired
    private HelpTaskRepository helpTaskRepository;
    @Autowired
    private HelpTakeOrderRepository helpTakeOrderRepository;
    /** 接单信息自定义方法类 */
    @Autowired
    private HelpSendOrderRepository helpSendOrderRepository;
    /** 用户钱包明细 */
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    /** 用户信息 */
    @Autowired
    private UserRepository userRepository;
    /** 信誉分 */
    @Autowired
    private HelpUserScoreService helpUserScoreService;
    /** 信誉明细分 */
    @Autowired
    private HelpUserScoreDetailsService helpUserScoreDetailsService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IMoneyDetailsService moneyDetailsService;

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 获取已经结束的助力任务
     */
    @Scheduled(cron="0 */1 * * * ?")
    public void getEndTask() {
        List<TimedTask> list=timedTaskRepository.selectEndTime();
        if(list.size()>0){
            //先将所有的定时任务进行删除 防止业务处理时间过长导致重复处理
            timedTaskJpaRepository.deleteAll(list);
            //执行定时任务中的计划
            for(TimedTask timedTask:list){
                if(timedTask.getType()==1){//修改助力活动的状态
                    updateHelpTask(timedTask);
                }else if(timedTask.getType()==2){//修改参加活动的状态
                    updateSendOrderState5(timedTask);
                }else if(timedTask.getType()==3){//
                    updateSendOrderState2(timedTask);
                }
            }
        }
    }


    //修改助力活动方法
    @Transactional
    public void updateHelpTask(TimedTask timedTask){
        //获取我的派单信息
        HelpTakeOrder helpTakeOrder=helpTakeOrderRepository.selectHelpTakeOrderByHelpTaskId(timedTask.getObjectId());
        if(helpTakeOrder!=null){
            //修改助力活动状态为结束
            helpTaskRepository.updateHelpTaskState(2,timedTask.getObjectId());
            //修改我的派单信息为结束
            helpTakeOrderRepository.updateHelpTakeOrder(helpTakeOrder.getState(),helpTakeOrder.getId(),"已结束",0);
            UserInfo userByWxId = userRepository.getUserById(helpTakeOrder.getUserId());
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent(userByWxId.getNickName() + " 您好！您的派单时间已经结束了！请尽快去我的派单中点击结算，结束任务id："+helpTakeOrder.getHelpTaskId());
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("派单结束", userByWxId.getNickName() + " 您好！您的派单时间已经结束了！请尽快去我的派单中点击结算，结束任务id："+helpTakeOrder.getHelpTaskId(), userByWxId.getClientid());
            }
            messageInfo.setState(String.valueOf(6));
            messageInfo.setTitle("派单结束");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
        }
    }

    //修改接单助力活动为延期状态
    @Transactional
    public void updateSendOrderState5(TimedTask timedTask){
        HelpSendOrder helpSendOrder=helpSendOrderRepository.selectById(timedTask.getObjectId());
        if(helpSendOrder!=null){
            //修改接单状态
            helpSendOrderRepository.updateHelpSendOrder(timedTask.getObjectId(),5,"已延期",0,null);
            //超时未提交扣除信用分
            helpUserScoreService.updateUserScore(helpSendOrder.getUserId(),2,1);
            HelpUserScoreDetails helpUserScoreDetails=new HelpUserScoreDetails();
            helpUserScoreDetails.setUserId(helpSendOrder.getUserId());
            helpUserScoreDetails.setTitle("任务超时，Id："+helpSendOrder.getHelpTaskId());
            helpUserScoreDetails.setContent("扣除积分：1");
            helpUserScoreDetails.setCreateTime(sdf.format(new Date()));
            helpUserScoreDetails.setScore(1);
            helpUserScoreDetails.setType(2);
            helpUserScoreDetailsService.save(helpUserScoreDetails);
            UserInfo userByWxId = userRepository.getUserById(helpSendOrder.getUserId());
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent(userByWxId.getNickName() + " 您好！您的接单任务已经延期！");
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("接单延期", userByWxId.getNickName() + " 您好！您的接单任务已经延期！已扣除您的信誉分:1分，请您遵守规定按时完成任务，信誉值较低则无法体现！", userByWxId.getClientid());
            }
            messageInfo.setState(String.valueOf(6));
            messageInfo.setTitle("接单延期");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
        }
    }

    //修改接单助力活动为通过状态
    @Transactional
    public void updateSendOrderState2(TimedTask timedTask){
        HelpSendOrder helpSendOrder=helpSendOrderRepository.selectById(timedTask.getObjectId());
        if(helpSendOrder!=null){
            //修改接单状态
            helpSendOrderRepository.updateHelpSendOrder(timedTask.getObjectId(),2,"已同意",0,sdf.format(new Date()));
            //给接单人增加金额

            HelpTask helpTask= helpTaskRepository.selectById(helpSendOrder.getHelpTaskId());
            DecimalFormat formater = new DecimalFormat();
            formater.setMaximumFractionDigits(2);
            formater.setGroupingSize(0);
            formater.setRoundingMode(RoundingMode.FLOOR);
            Double money=Double.parseDouble(formater.format(helpTask.getTaskPrice()));
            userRepository.updateJiFenAdd(money.toString(),helpSendOrder.getUserId());
            MoneyDetails userMoneyDetails=new MoneyDetails();
            userMoneyDetails.setUserId(helpSendOrder.getUserId());
            userMoneyDetails.setTitle("[完成任务]任务ID："+helpTask.getId());
            userMoneyDetails.setContent("增加金额:"+money);
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(money);
            userMoneyDetails.setCreateTime(sdf.format(new Date()));
            moneyDetailsService.save(userMoneyDetails);
            //删除定时任务
            timedTaskJpaRepository.deleteById(timedTask.getId());
            //完成接单增加信誉分
            helpUserScoreService.updateUserScore(helpSendOrder.getUserId(),1,1);
            HelpUserScoreDetails helpUserScoreDetails=new HelpUserScoreDetails();
            helpUserScoreDetails.setUserId(helpSendOrder.getUserId());
            helpUserScoreDetails.setTitle("[完成任务]任务Id："+helpSendOrder.getHelpTaskId());
            helpUserScoreDetails.setContent("增加积分：1");
            helpUserScoreDetails.setCreateTime(sdf.format(new Date()));
            helpUserScoreDetails.setScore(1);
            helpUserScoreDetails.setType(1);
            helpUserScoreDetailsService.save(helpUserScoreDetails);
            UserInfo userByWxId = userRepository.getUserById(helpSendOrder.getUserId());
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent(userByWxId.getNickName() + " 您好！您的接单任务已经通过！");
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("接单通过", userByWxId.getNickName() + " 您好！您的接单任务已经通过！接单id:"+helpSendOrder.getId(), userByWxId.getClientid());
            }
            messageInfo.setState(String.valueOf(6));
            messageInfo.setTitle("接单通过");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
        }
    }


}
